//
//  XCSMSCodeInputView.m
//  HOLLASMSLoginKit
//
//  Created by Mars on 2019/10/12.
//  Copyright © 2019 mao PengLin. All rights reserved.
//

#import "XCSMSCodeInputView.h"
#import "Config.h"
#import "XCSMSTheme.h"
#import "XCSMSTextField.h"

@interface XCSMSCodeInputView() <UITextFieldDelegate, XCSMSTextFieldDelegate>

@property (nonatomic, strong) NSMutableArray<XCSMSTextField *> *textFields;
@property (nonatomic, assign) NSUInteger codeDigit;

@end

@implementation XCSMSCodeInputView

- (instancetype)initWithFrame:(CGRect)frame selectCodeBlock:(XCSMSSelectCodeBlock)CodeBlock{
    self = [super initWithFrame:frame];
    if (self) {
        self.codeBlock = CodeBlock;
        
        self.codeDigit = [XCSMSTheme sharedTheme].useFirebasePhoneAuth ? 6 : 4;
        _textFields = [NSMutableArray arrayWithCapacity:self.codeDigit];
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    
    CGFloat labelHeight = self.frame.size.height;
    CGFloat sideMargin = 44;
    CGFloat textViewWidth = HWScreenWidth - sideMargin * 2;
    CGFloat labelInterval = 16;                  //输入框间距
    CGFloat labelWidth = (textViewWidth - labelInterval * (self.codeDigit - 1))/self.codeDigit;        //单个输入框宽度
    CGFloat posX = 0;
    
    if (SMSIsArabic()) {
        for (int i = (int)self.codeDigit - 1; i >= 0; i--) {
            posX = ( labelWidth + labelInterval) * i + sideMargin;
            XCSMSTextField *textField = [self smsTextField];
            textField.frame = CGRectMake(posX, 0, labelWidth, labelHeight);
            [self addSubview:textField];
        }
    } else {
        for (int i = 0; i < self.codeDigit; i++) {
            posX = ( labelWidth + labelInterval) * i + sideMargin;
            XCSMSTextField *textField = [self smsTextField];
            textField.frame = CGRectMake(posX, 0, labelWidth, labelHeight);
            [self addSubview:textField];
        }
    }
    
    [[_textFields firstObject] becomeFirstResponder];
    
    CGPoint startPoint = CGPointMake(0, 0);
    CGPoint endPoint = CGPointMake(textViewWidth, 0);
    UIBezierPath *linePathYear = [UIBezierPath bezierPath];
    [linePathYear moveToPoint:startPoint];
    [linePathYear addLineToPoint:endPoint];
    
    CAShapeLayer *dashedUnderlineLayer = [CAShapeLayer layer];
    dashedUnderlineLayer.strokeColor = [XCSMSTheme sharedTheme].inputTextColor.CGColor;
    dashedUnderlineLayer.fillColor = nil;
    dashedUnderlineLayer.lineDashPattern = @[@(labelWidth), @(labelInterval)];
    dashedUnderlineLayer.lineWidth = 1;
    dashedUnderlineLayer.frame = CGRectMake(sideMargin, labelHeight - 1, textViewWidth, 1);
    dashedUnderlineLayer.path = linePathYear.CGPath;
    [self.layer addSublayer:dashedUnderlineLayer];
}

- (XCSMSTextField *)smsTextField {
    XCSMSTextField *textField = [[XCSMSTextField alloc] init];
    textField.backgroundColor = [UIColor clearColor];
    textField.font = MediumFont(18);
    textField.textColor = [XCSMSTheme sharedTheme].inputTextColor;
    textField.textAlignment = NSTextAlignmentCenter;
    textField.borderStyle = UITextBorderStyleNone;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.adjustsFontSizeToFitWidth = false;
    textField.delegate = self;
    textField.tintColor = [XCSMSTheme sharedTheme].inputCursorColor;
    textField.deleteDelegate = self;
    [_textFields addObject:textField];
    [textField addTarget:self action:@selector(textFieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];
    if (@available(iOS 12.0, *)) {
        textField.textContentType = UITextContentTypeOneTimeCode;
    }
    return textField;
}

- (NSInteger)nextIndex:(NSInteger)currentIndex {
    return MIN(currentIndex + 1, self.codeDigit - 1);
}

- (NSInteger)prevIndex:(NSInteger)currentIndex {
    return MAX(currentIndex - 1, 0);
}

- (void)endEdit {
    for (UITextField *textField in _textFields) {
        [textField resignFirstResponder];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length && ![self chcekIsNumberWithString:string]) { //如果包含非数字，则全部拒绝替换
        return NO;
    }
    if (string.length > 1 ) {
        return  NO;
    }
    return YES;
}

//检测是否是数字
- (BOOL)chcekIsNumberWithString:(NSString *)string {
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

- (void)textFieldTextDidChange:(UITextField *)textField {
    NSString *code = @"";
    for (int i = 0; i < [_textFields count]; i++) {
        if ([_textFields[i].text length] > 0) {
            code = [code stringByAppendingString:_textFields[i].text];
        }
    }
    
    NSInteger index = [_textFields indexOfObject:(XCSMSTextField *)textField];
    if ([textField.text length] > 0 && index < [_textFields count] - 1) {
        NSInteger nextIndex = [self nextIndex:index];
        [_textFields[nextIndex] becomeFirstResponder];
    }
    
    if (self.codeBlock) {
        self.codeBlock([code length] >= self.codeDigit, code);
    }
    
    if ([code length] >= self.codeDigit) {
        [self endEdit];
    }
}

#pragma mark - HWDateTextFieldDelegate
- (void)textFieldDeleteEvent:(UITextField *)textField {
    if ([textField.text length] == 0) {
        NSInteger index = [_textFields indexOfObject:(XCSMSTextField *)textField];
        if (index > 0) {
            NSInteger prevIndex = [self prevIndex:index];
            [_textFields[prevIndex] becomeFirstResponder];
            _textFields[prevIndex].text = @"";
        }
    }
}

@end
